package com.zjh.util;

import org.apache.ibatis.io.Resources;
import org.apache.ibatis.session.SqlSession;
import org.apache.ibatis.session.SqlSessionFactory;
import org.apache.ibatis.session.SqlSessionFactoryBuilder;

import java.io.IOException;
import java.io.Reader;


/**
 * @author LiZiQiu
 * @data 2023/3/7
 */
public class sqlSessionUtil {
    private static ThreadLocal<SqlSession> threadLocal  = new ThreadLocal<>();
    private static SqlSessionFactory sqlSessionFactory;


    static {
        try {
            Reader reader = Resources.getResourceAsReader("mybatis-config.xml");
            sqlSessionFactory = new SqlSessionFactoryBuilder().build(reader,"a2");
        } catch (IOException e) {
            e.printStackTrace();
        }
    }

    public static SqlSession getSession() {
        SqlSession session = threadLocal.get();
        if(session==null) {
            session = sqlSessionFactory.openSession();
            threadLocal.set(session);
        }
        return session;
    }
    public static void closeSession() {
        SqlSession session = threadLocal.get();
        if(session!=null) {
            session.close();
            threadLocal.remove();
        }

    };


}
